package cn.larry.common.utils.wx;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import cn.larry.common.utils.DateUtils;
import cn.larry.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * This is created,
 * but not necessarily updated by me.
 * Therefore, AUTHOR is useless.
 * 2024/5/28 09:06
 * 【汇报】
 * 参考：https://developer.work.weixin.qq.com/document/path/93496
 *
 * @Version 1.0
 */
@Slf4j
@Component
public class QywxReportsTool {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取某一天的所有汇报记录单号
     *
     * @param token
     * @param dateStr
     * @return
     */
    public JSONArray getRecordList(String token, @NotNull String dateStr) {
        if (StringUtils.isEmpty(dateStr))
            return null;
        int cursor = 0;
        Date date = DateUtils.dateTime("yyyy-MM-dd", dateStr);
        Map<String, Object> result = getRecordList(token,
                date.getTime() / 1000,// 0点Unix时间戳
                (date.getTime() + 24 * 60 * 60 * 1000) / 1000,// 次日0点Unix时间戳
                cursor);
        if (!"0".equals(result.get("errcode").toString())) {
            throw new RuntimeException("getRecordList error : " + result.get("errmsg"));
        }
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(result.get("journaluuid_list")));
        String endflag = result.get("endflag").toString();
        while ("0".equals(endflag)) {
            cursor = Integer.valueOf(result.get("cursor").toString());
            result = getRecordList(token,
                    date.getTime() / 1000,// 0点Unix时间戳
                    (date.getTime() + 24 * 60 * 60 * 1000) / 1000,// 次日0点Unix时间戳
                    cursor);
            if (!"0".equals(result.get("errcode").toString()))
                break;
            jsonArray.addAll(JSONArray.parseArray(JSON.toJSONString(result.get("journaluuid_list"))));
            endflag = result.get("endflag").toString();
        }
        return jsonArray;
    }

    /**
     * 分批获取某一天的汇报记录单号
     *
     * @param token
     * @param dateStr 查询日期（格式：yyyy-MM-dd）
     * @param cursor  游标（默认'0'）
     * @return
     * @throws Exception
     */
    public JSONArray getRecordList(String token,
                                   @NotNull String dateStr, int cursor) {
        if (StringUtils.isEmpty(dateStr))
            return null;
        if (cursor < 0)
            cursor = 0;

        Date date = DateUtils.dateTime("yyyy-MM-dd", dateStr);
        Map<String, Object> result = getRecordList(token,
                date.getTime() / 1000,// 0点Unix时间戳
                (date.getTime() + 24 * 60 * 60 * 1000) / 1000,// 次日0点Unix时间戳
                cursor);
//        log.info("微信应答：{}", result);
        if (!"0".equals(result.get("errcode").toString())) {
            throw new RuntimeException("getRecordList error : " + result.get("errmsg"));
        }
        return JSONArray.parseArray(JSON.toJSONString(result.get("journaluuid_list")));
    }

    /**
     * 批量获取汇报记录单号
     *
     * @param token
     * @param starttime
     * @param endtime
     * @param cursor
     * @return
     */
    private Map<String, Object> getRecordList(String token,
                                              Long starttime, Long endtime, int cursor) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("starttime", starttime);// 开始Unix时间戳
        paramMap.put("endtime", endtime);// 结束Unix时间戳
        paramMap.put("cursor", cursor);
        paramMap.put("limit", 200);// 本人2024-03-14试过，这里最大只能使用'200'
        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("token", token);
        String postUrl = "https://qyapi.weixin.qq.com/cgi-bin/oa/journal/get_record_list?access_token={token}";
        return restTemplate.postForObject(postUrl, JSON.toJSONString(paramMap), Map.class, uriVariables);
    }

    /**
     * 获取汇报详情内容
     *
     * @param token
     * @param journaluuid 汇报记录ID
     * @return
     */
    public JSONObject getRecordDetail(String token, String journaluuid) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("journaluuid", journaluuid);
        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("token", token);

        String postUrl = "https://qyapi.weixin.qq.com/cgi-bin/oa/journal/get_record_detail?access_token={token}&debug=1";
        Map<String, Object> result = restTemplate.postForObject(postUrl, JSON.toJSONString(paramMap), Map.class, uriVariables);
//        log.info("微信应答：{}", result);
        if (!"0".equals(result.get("errcode").toString())) {
            throw new RuntimeException("getRecordList error : " + result.get("errmsg"));
        }
        return JSONObject.parseObject(JSON.toJSONString(result.get("info")));
    }

}
